
package com.ifcar.app.activity.comment;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.ifcar.app.activity.CommonFrameActivity;
import com.ifcar.app.activity.NewsPage;
import com.ifcar.app.activity.common.CommentFragment;
import com.ifcar.app.activity.newspage.NewsCommentFragment;
import com.ifcar.app.fragment.NRAbsPullLoadingListFrament;
import com.ifcar.app.model.CommentRank;
import com.ifcar.app.rss.GetColumnsInfo;
import com.ifcar.app.rss.GetComments;
import com.ifcar.app.util.BasePageViewAdapter;
import com.ifcar.app.util.ModelUtils;
import com.ifcar.app.util.StringUtil;
import com.ifcar.app.view.LoadingListView;
import com.ifcar.app.activity.R;

import org.json.JSONException;
import org.json.JSONObject;

public class CommentRankFragment extends NRAbsPullLoadingListFrament implements OnItemClickListener {

    private BasePageViewAdapter mAdapter;

    private List<Map<String, Object>> mData;

    private String mType;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRefreshTag(getTag());
        Bundle args = getArguments();
        if (args != null) {
            mType = args.getString("type");
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mAdapter != null) {
            mAdapter.notifyDataSetChanged();
        }
    }

    @Override
	public ListAdapter getAdapter() {
		return mAdapter;
	}

	@Override
	public void onLoadingListViewAttached(LoadingListView loadingListView) {
		super.onLoadingListViewAttached(loadingListView);
        loadingListView.getListView().setOnItemClickListener(this);
        if (mAdapter != null && mAdapter.getCount() > 0) {
            callLoadingListViewAddMoreView();
        }
	}

	@Override
    public void onTabSelected(boolean first) {
        super.onTabSelected(first);
        if (first) {
            startLoading();
        }
    }

    @Override
    protected void onLoading() {
        super.onLoading();

        // 加载本地数据,没有启用新线程
        List<Map<String, Object>> list = CommentRank.getRankCommentsFromDB(getDb(), mType);
        Message msg = getHandler().obtainMessage(MSG_LOADING);
        msg.obj = list;
        getHandler().dispatchMessage(msg);
    }

    @Override
    protected void onHandleLoading(Object result) {
        super.onHandleLoading(result);
        List<Map<String, Object>> list = (List<Map<String, Object>>) result;
        
        
        if (list != null && list.size() > 0) {
            callLoadingListViewAddMoreView();
        } else if (mAdapter == null || mAdapter.getCount() == 0) {
            callLoadingListViewRemoveMoreView();
        }
        
        setData(list);

        if (mAdapter != null && mAdapter.getCount() > 0) {
            if (isNeedRefresh()) {
                getHandler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        refresh();
                    }
                }, 200);
            }
        } else {
            refresh();
        }
    }

    @Override
    protected void onRefreshing() {
        super.onRefreshing();

        callLoadingListViewStartLoading(mAdapter == null);

        final Context context = getActivity();
        final SQLiteDatabase db = getDb();
        final int num = getLoadingNum();

        new Thread(new Runnable() {
            @Override
            public void run() {
                // 取网络
                List<Map<String, Object>> list = CommentRank.getRankComments(context, db, mType, 0,
                        num);

                if (list != null && list.size() > 0) {
                    StringUtil.updateRefreshTime(context, getRefreshTag());
                }

                Message msg = getHandler().obtainMessage(MSG_REFRESHING);
                msg.obj = list;
                getHandler().sendMessage(msg);
            }
        }).start();
    }

    @Override
    protected void onHandleRefreshing(Object result) {
        super.onHandleRefreshing(result);

        List<Map<String, Object>> topicData = (List<Map<String, Object>>) result;
        
        
        if (topicData != null && topicData.size() > 0) {
            callLoadingListViewAddMoreView();
        }

        if (topicData != null && topicData.size() != 0) {
            callLoadingListViewCompleteLoading(true, true);
            setData(topicData);
        } else {
            Toast.makeText(getActivity(), R.string.msg_loading_failed, Toast.LENGTH_SHORT).show();
            callLoadingListViewCompleteLoading(false, true);
        }
    }

    @Override
    protected void onLoadingMore() {
        super.onLoadingMore();
        if (!"top".equals(mType)) {
            getHandler().sendEmptyMessage(MSG_LOADING_MORE);
            return;
        }

        final Context context = getActivity();
        final SQLiteDatabase db = getDb();
        final int num = getLoadingNum();
        final int start = (mData == null || mData.size() == 0) ? 0 : getLoadingStart() + num;
        callLoadingListViewStartLoadingMore(start);
        // 取网络
        new Thread(new Runnable() {
            @Override
            public void run() {
                List<Map<String, Object>> list = CommentRank.getRankComments(context, db, mType, start, num);
                
                Message msg = getHandler().obtainMessage(MSG_LOADING_MORE);
                msg.obj = list;
                getHandler().sendMessage(msg);
            }
        }).start();
    }

    @Override
    protected void onHandleLoadingMore(Object result) {
        super.onHandleLoadingMore(result);

        List<Map<String, Object>> data = (List<Map<String, Object>>) result;
        if (data != null && data.size() != 0) {
            callLoadingListViewCompleteLoadingMore(true, true);
            addData(data);
        } else {
            Toast.makeText(getActivity(), R.string.msg_loading_failed, Toast.LENGTH_SHORT).show();
            callLoadingListViewCompleteLoadingMore(false, true);
        }

    }

    private void setData(List<Map<String, Object>> data) {
        if (data != null && data.size() > 0) {
            mData = data;
            if ("top".equals(mType)) {
                mAdapter = new BasePageViewAdapter(getActivity(), mData,
                        R.layout.top_comments_item, new String[] {
                                GetComments.TIE_TAG, GetComments.AUTHOR_TAG, GetComments.TITLE_TAG
                        }, new int[] {
                                R.id.top_comments_content, R.id.top_comments_username,
                                R.id.top_comments_source
                        }, null);
                mAdapter.setAdapterType("top_comments");
            } else if ("day".equals(mType)) {
                mAdapter = new BasePageViewAdapter(getActivity(), mData,
                        R.layout.comments_rank_item, new String[] {
                                GetColumnsInfo.REPLYCOUNT_TAG, GetColumnsInfo.TITLE_TAG
                        }, new int[] {
                                R.id.reply_count, R.id.rank_comments_source
                        }, null);
                mAdapter.setAdapterType("day_rank");
            } else if ("week".equals(mType)) {
                mAdapter = new BasePageViewAdapter(getActivity(), mData,
                        R.layout.comments_rank_item, new String[] {
                                GetColumnsInfo.REPLYCOUNT_TAG, GetColumnsInfo.TITLE_TAG
                        }, new int[] {
                                R.id.reply_count, R.id.rank_comments_source
                        }, null);
                mAdapter.setAdapterType("week_rank");
            }

            mAdapter.setDB(getDb());

            ListView listView = getListView();
            if (listView != null) {
                listView.setAdapter(mAdapter);
            }

        }
    }

    private void addData(List<Map<String, Object>> data) {
        if (data == null || data.size() == 0 || mData == null) {
            return;
        }
        mData.addAll(data);
        if (mAdapter != null) {
            mAdapter.notifyDataSetChanged();
        }
    }

    public String getType() {
        return mType;
    }

    @Override
    public boolean hasMoreView() {
        return "top".equals(mType);
    }

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        
        Map<String, Object> map = mData.get(arg2);
        
        Bundle bundle;

        try {
            String boardId = (String)ModelUtils.getValue(map, GetComments.REPLYBOARD_TAG);
            String docId = "top".equals(mType) ? (String) ModelUtils.getValue(map,
                    GetComments.DOCID_TAG) : (String) ModelUtils.getValue(map,
                    GetComments.POSTID_TAG);
            String p = (String)ModelUtils.getValue(map, GetComments.FLOOR_TAG);
            String title = (String)ModelUtils.getValue(map, GetComments.TITLE_TAG);
            JSONObject jsonObj = new JSONObject();
            try {
                jsonObj.put(GetComments.P_TAG, p==null?"":p);
                jsonObj.put(GetColumnsInfo.POSTID_TAG, docId);
                jsonObj.put(GetColumnsInfo.REPLYBOARD_TAG, boardId);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            String url = jsonObj.toString();
            
            bundle = new Bundle();
            bundle.putString(CommentFragment.BOARD_ID, boardId);
            bundle.putString(CommentFragment.DOC_ID, docId);
            bundle.putString(CommentFragment.DOC_TITLE, title);
            bundle.putString(CommentFragment.COMMENT_URL, url);
            
            String type = "top".equals(mType) ? null : mType;
            bundle.putString(CommentFragment.COMMENT_TYPE, type);
            
            if ("top".equals(mType)) {                   
                bundle.putString(CommentFragment.TOP_P, p); 
            } 
        } catch (Exception e) {
            e.printStackTrace();
            bundle = null;
        }

        if (bundle == null) {
            return;
        }

        Intent intent = new Intent(getActivity(), NewsPage.class);
        intent.putExtra(NewsCommentFragment.PARAM_FOR_COMMENT, bundle);
        intent.putExtra(NewsCommentFragment.PARAM_FROM_COMMENT, true);
        startActivity(intent);
        
    }
    
    @Override
    public void onApplyTheme() {
        super.onApplyTheme();
        if (mAdapter != null) {
            mAdapter.notifyDataSetChanged();
        }
    }

}
